package com.longteng.diamond.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.longteng.diamond.domain.InterfaceMock;
import com.longteng.diamond.domain.InterfaceMockData;
import com.longteng.diamond.service.MockMatchDataService;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator
 * DATE : 2018/8/12
 * TIME : 9:55
 * PROJECT : java-lesson
 * PACKAGE : com.longteng.lesson
 *
 * @author <a href="mailto:taki@qq.com">Administrator</a>
 */
@Component
public class KeyValueMatchImpl implements MockMatchDataService {
    /**
     * 通过keyValue的方法获取mock数据
     * @param
     * @return mockData
     */
    @Override
    public String dataMatch(InterfaceMock interfaceMock, List<InterfaceMockData> interfaceMockDataList, HttpServletRequest httpRequest) {
        for (InterfaceMockData interfaceMockData : interfaceMockDataList) {
            String data = interfaceMockData.getMatchData();
            /**反序列化匹配数据,转换成map类型**/
            Map<String,String> map= JSON.parseObject(data,new TypeReference<HashMap<String,String>>(){});
            boolean isMatch=true;
            for(String key:map.keySet()){
                String dbValue =map.get(key);
                String paramValue= httpRequest.getParameter(key);
                /**如果他们两个相等说明匹配上了**/
                if(null==paramValue || !dbValue.equalsIgnoreCase(paramValue)){
                    isMatch=false;
                    break;
                }
            }
            if(isMatch){
                return interfaceMockData.getMockData();
            }
        }
        return "未找到匹配的mock数据";
    }
}
